<template>
	<div class="main">
        <div class="header">
            <a href="/"><img width="100" src="../../assets/img/logo3.png" alt=""></a>
            <h1>用户登录</h1>
        </div>
        <form @submit.prevent="loginHandler">
            <div class="form-group">
                <label for="email">邮箱</label>
                <input required v-model="formData.email" type="email" id="email" class="form-control" placeholder="Email">
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <a class="pull-right" href="">忘记密码？</a>
                <input required v-model="formData.password" type="password" id="password" class="form-control" placeholder="Password">
            </div>
            <div class="checkbox">
                <label>
                    <input type="checkbox">记住我
                </label>
            </div>
            <p class="error-message" v-show="loginMessage">{{ loginMessage }}</p>
            <button type="submit" class="btn btn-success btn-block">登录</button>
        </form>
        <div class="message">
            <p>没有账号? <router-link to="/register">点击创建</router-link>.</p>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
import _ from 'lodash'

export default {
	data () {
		return {
			formData : {
				email : '',
				password : ''
			},
      loginMessage : ''
		}
	},
	methods : {
		loginHandler : _.debounce (async function () {
      try {
        const ret = await axios.post('/api/session', this.formData)
        this.loginMessage = ''
        // this.$router.push('/')
        this.$router.back()
      } catch(err) {
        const {status} = err.response
        switch (status) {
          case 404:
            this.loginMessage = '用户名或者密码不正确!'
            break;
        }
      }
    }, 500)
	}
}
</script>

<style>
body {
  background-color: #f9f9f9;
}

.main {
  width: 340px;
  margin: 0 auto;
  margin-top: 50px;
  color: #333;
}

.main .header {
  text-align: center;
}

.main .header h1 {
  font-size: 26px;
}

.main form {
  padding: 20px;
  margin-bottom: 15px;
  border: 1px solid #d8dee2;
  border-radius: 5px;
  background-color: #fff;
}

.main .message {
  padding: 10px;
  padding-bottom: 0;
  border: 1px solid #d8dee2;
  border-radius: 5px;
}	
</style>
